/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */
//  class TreeNode {
//     val: number
//     left: TreeNode | null
//     right: TreeNode | null
//     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
//         this.val = (val === undefined ? 0 : val)
//         this.left = (left === undefined ? null : left)
//         this.right = (right === undefined ? null : right)
//     }
// }

function levelOrder_2(root: TreeNode | null): number[][] {
    let result: number[][] = new Array<Array<number>>();
    let from: TreeNode[];
    let to: TreeNode[] = new Array<TreeNode>();
    let key = 0;

    if (root == null) {
        return result;
    }
    to.push(root);

    while (to.length > 0) {
        result[key] = new Array<number>();
        from = to;
        to = new Array<TreeNode>();;
        while (from.length > 0) {
            let node = from.shift();
            if (node != null) {
                result[key].push(node.val);
                if (node.left) {
                    to.push(node.left);
                }
                if (node.right) {
                    to.push(node.right);
                }
            }
        }
        key++;
    }

    return result;
};
// let result: number[][] = new Array<Array<number>>();
// result[0] = new Array<number>();
// console.log(result);
// console.log(result[0]);
